package cn.school.demo.ui.point_datails

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentPointDetailsBinding
import cn.school.demo.pojo.IntegralDetails
import cn.school.demo.ui.my_view.DividerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

class PointDetailsFragment : Fragment() {
    private lateinit var viewModel: PointDetailsViewModel
    private lateinit var binding: FragmentPointDetailsBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        MyApplication.systemBarSetting(MyApplication.DARK, requireActivity())
        viewModel = ViewModelProvider(this).get(PointDetailsViewModel::class.java)
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_point_details, container, false)
        binding.vw = this
        binding.lifecycleOwner = viewLifecycleOwner
        init()
        return binding.root
    }

    @SuppressLint("NewApi", "NotifyDataSetChanged")
    fun init() {
        viewModel.integralDetailsList.observe(viewLifecycleOwner) {
            LogUtils.e(it.toString())
            if (it.isNotEmpty()) {
                viewModel.apply {
                    classifyIntegralDetailsList()
                    setTimeList()
                    classifyMapList[LocalDate.now().toString()]?.let {
                        LogUtils.e(
                            it,
                            classifyMapAllPointList[LocalDate.now().toString()]!!,
                            classifyMapAllPointList.toString()
                        )
                        val item = it[0]
                        updateThisDateItem(
                            IntegralDetails(
                                item.integralId,
                                item.userSfNumber,
                                item.integralSource,
                                classifyMapAllPointList[LocalDate.now().toString()]!!,
                                item.integralTime
                            )
                        )
                        updateThisList(it)
                    } ?: let {
                        updateThisDateItem(
                            IntegralDetails(
                                -1,
                                MyApplication.user!!.sfNumber,
                                "无",
                                0,
                                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:SS:MM")
                                    .format(LocalDateTime.now())
                            )
                        )
                        updateThisList(mutableListOf())
                    }
                }
                binding.pointDetailsBarChartRl.apply {
                    val _adapter = IntegralDetailHorizontalAdapter(viewModel.timeList)
                    //_adapter.setHasStableIds(true)
                    adapter = _adapter
                    val layoutManager = LinearLayoutManager(requireContext())
                    layoutManager.orientation = LinearLayoutManager.HORIZONTAL
                    this.layoutManager = layoutManager
                    layoutManager.scrollToPositionWithOffset(31, 0)
                }
                binding.pointDetailsThingRecyclerView.apply {
                    LogUtils.e(viewModel.thisItemRecycleViewList.value!!)
                    this.layoutManager = LinearLayoutManager(requireContext())
                    this.adapter = IntegralDetailAdapter(viewModel.thisItemRecycleViewList.value!!)
                }

            } else {
                viewModel.setTimeList()
                binding.pointDetailsBarChartRl.apply {
                    adapter = IntegralDetailHorizontalAdapter(viewModel.timeList)
                    val layoutManager = LinearLayoutManager(requireContext())
                    layoutManager.orientation = LinearLayoutManager.HORIZONTAL
                    this.layoutManager = layoutManager
                }
            }
        }
        viewModel.observeData.observe(viewLifecycleOwner) {
            LogUtils.e(it)
            LogUtils.e("我执行l=")
            binding.pointDetailsThingRecyclerView.adapter?.notifyDataSetChanged()
                ?: LogUtils.e("我为空了！！")
        }
        viewModel.thisDateItem.observe(viewLifecycleOwner) {
            binding.apply {
                pointDetailsDate.text = it.integralTime.subSequence(0, 10)
                val text_f = SpannableString("当日积分: ${it.integralAccount} ")
                text_f.setSpan(
                    ForegroundColorSpan(Color.parseColor("#ff0000")),
                    0,
                    text_f.length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                val text_s = SpannableString("(年度积分: ${MyApplication.user!!.totalIntegral})")
                text_s.setSpan(
                    ForegroundColorSpan(Color.parseColor("#2696ff")),
                    0,
                    text_s.length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )

                pointDetailsDayPoint.apply {
                    text = ""
                    append(text_f)
                    append(text_s)
                }
            }
        }
    }

    fun gotoMy() = MyApplication.goto(
        R.id.action_PointDetail_to_My,
        findNavController(),
        parentFragmentManager
    )

    private inner class IntegralDetailHolder(view: View) : RecyclerView.ViewHolder(view) {
        private lateinit var integralDetail: IntegralDetails
        private val timeTextView =
            itemView.findViewById<TextView>(R.id.fragment_point_details_time)
        private val sourceTextView =
            itemView.findViewById<TextView>(R.id.fragment_point_details_source)
        private val pointTextView =
            itemView.findViewById<TextView>(R.id.fragment_point_details_point)
        val LineUp: DividerView
        val LineDown: DividerView

        init {
            LineUp = itemView.findViewById(R.id.line_up)
            LineDown = itemView.findViewById(R.id.line_down)
        }

        @SuppressLint("SetTextI18n")
        fun bind(point: IntegralDetails) {
            this.integralDetail = point
            timeTextView.text = this.integralDetail.integralTime.subSequence(11, 16)
            sourceTextView.text = this.integralDetail.integralSource
            pointTextView.text = "+${this.integralDetail.integralAccount}分"
        }
    }

    private inner class IntegralDetailAdapter(var pointsList: MutableList<IntegralDetails>) :
        RecyclerView.Adapter<IntegralDetailHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IntegralDetailHolder {
            val view = layoutInflater.inflate(R.layout.list_item_point_detail, parent, false)
            return IntegralDetailHolder(view)
        }

        override fun onBindViewHolder(holder: IntegralDetailHolder, position: Int) {
            val point = pointsList[position]
            holder.LineUp.visibility = if (position == 0) View.INVISIBLE else View.VISIBLE
            holder.LineDown.visibility =
                if (position == pointsList.size - 1) View.INVISIBLE else View.VISIBLE
            holder.bind(point)
        }

        override fun getItemCount() = pointsList.size
    }

    private inner class IntegralDetailHorizontalHolder(view: View) : RecyclerView.ViewHolder(view),
        View.OnClickListener {
        private lateinit var integralDetailMap: IntegralDetails
        private val timeTextView =
            itemView.findViewById<TextView>(R.id.horizontal_rl_time)
        private val imageView =
            itemView.findViewById<ImageView>(R.id.horizontal_rl_image)
        private val pointTextView =
            itemView.findViewById<TextView>(R.id.horizontal_rl_point)

        init {
            itemView.setOnClickListener(this)
        }

        @SuppressLint("SetTextI18n")
        fun bind(map: IntegralDetails) {
            this.integralDetailMap = map
            if (this.integralDetailMap.integralTime == "" && this.integralDetailMap.integralAccount == -1) {
                timeTextView.text = ""
                val lp = imageView.layoutParams
                lp.height = 0
                lp.width = (ScreenUtils.getAppScreenWidth() * 0.12).toInt()
                imageView.layoutParams = lp
                pointTextView.text = ""
            } else {
                timeTextView.text = this.integralDetailMap.integralTime.subSequence(5, 10)
                val lp = imageView.layoutParams
                lp.height = 15 * this.integralDetailMap.integralAccount
                lp.width = (ScreenUtils.getAppScreenWidth() * 0.12).toInt()
                imageView.layoutParams = lp
                pointTextView.text = "${this.integralDetailMap.integralAccount}分"
            }
            timeTextView.setTextColor(resources.getColorStateList(R.color.text_gray, null))
            pointTextView.setTextColor(resources.getColorStateList(R.color.text_gray, null))
            imageView.setImageResource(R.color.h_rl_point_detail)
            itemView.setBackgroundResource(R.color.pure_white)
        }

        @SuppressLint("SetTextI18n", "NewApi")
        fun bindSelected(map: IntegralDetails) {
            this.integralDetailMap = map
            if (this.integralDetailMap.integralTime == "" && this.integralDetailMap.integralAccount == -1) {
                timeTextView.text = ""
                val lp = imageView.layoutParams
                lp.height = 0
                lp.width = (ScreenUtils.getAppScreenWidth() * 0.12).toInt()
                imageView.layoutParams = lp
                pointTextView.text = ""
            } else {
                if (this.integralDetailMap.integralTime.subSequence(5, 10) ==
                    LocalDate.now().toString().subSequence(5, 10)
                )
                    timeTextView.text = "今日"
                else
                    timeTextView.text = this.integralDetailMap.integralTime.subSequence(5, 10)
                val lp = imageView.layoutParams
                lp.height = 15 * this.integralDetailMap.integralAccount
                lp.width = (ScreenUtils.getAppScreenWidth() * 0.12).toInt()
                imageView.layoutParams = lp
                pointTextView.text = "${this.integralDetailMap.integralAccount}分"
            }
            timeTextView.setTextColor(resources.getColorStateList(R.color.red, null))
            pointTextView.setTextColor(resources.getColorStateList(R.color.red, null))
            imageView.setImageResource(R.color.red)
            itemView.setBackgroundResource(R.color.h_rl_point_detail_selected)
        }

        @SuppressLint("NotifyDataSetChanged")
        override fun onClick(v: View) {
            if (this.integralDetailMap.integralTime != "") {
                viewModel.updateThisDateItem(this.integralDetailMap)
                viewModel.updateThisList(
                    viewModel.classifyMapList[this.integralDetailMap.integralTime]
                        ?: mutableListOf()
                )
                viewModel.setOldPosition(viewModel.nowPosition)
                viewModel.setNowPosition(layoutPosition)
                val layoutManager =
                    binding.pointDetailsBarChartRl.layoutManager as LinearLayoutManager
                layoutManager.scrollToPositionWithOffset(viewModel.oldPosition - 3, 0)
                binding.pointDetailsBarChartRl.adapter!!.notifyItemChanged(viewModel.oldPosition)
                layoutManager.scrollToPositionWithOffset(viewModel.nowPosition - 3, 0)
                binding.pointDetailsBarChartRl.adapter!!.notifyItemChanged(viewModel.nowPosition)
            }
        }
    }

    private inner class IntegralDetailHorizontalAdapter(var pointsMap: MutableList<IntegralDetails>) :
        RecyclerView.Adapter<IntegralDetailHorizontalHolder>() {
        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): IntegralDetailHorizontalHolder {
            val view = layoutInflater.inflate(R.layout.list_item_horizontal_rl_point, parent, false)
            return IntegralDetailHorizontalHolder(view)
        }

        @SuppressLint("NewApi")
        override fun onBindViewHolder(holder: IntegralDetailHorizontalHolder, position: Int) {
            val point = pointsMap[position]
            //LogUtils.e("onBindViewHolder执行了：${position}")
            if (position == viewModel.nowPosition)
                holder.bindSelected(point)
            else
                holder.bind(point)
        }

        override fun getItemCount() = pointsMap.size
    }


}
